package udp_syslog;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.apache.log4j.Logger;

import util.MyLog;

public class MyUdpServer {
	public static final int PORT = 30000;
	public static final String IP = "127.0.0.1";
	// 瀹氫箟姣忎釜鏁版嵁鎶ョ殑鏈�澶уぇ灏忎负4K
	private static final int DATA_LEN = 4096;
	// 瀹氫箟璇ユ湇鍔″櫒浣跨敤鐨凞atagramSocket
	private DatagramSocket socket = null;
	// 瀹氫箟鎺ユ敹缃戠粶鏁版嵁鐨勫瓧鑺傛暟缁�
	byte[] inBuff = new byte[DATA_LEN];
	// 浠ユ寚瀹氬瓧鑺傛暟缁勫垱寤哄噯澶囨帴鍙楁暟鎹殑DatagramPacket瀵硅薄
	private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
	// 瀹氫箟涓�涓敤浜庡彂閫佺殑DatagramPacket瀵硅薄
	private DatagramPacket outPacket;
	// 瀹氫箟涓�涓瓧绗︿覆鏁扮粍锛屾湇鍔″櫒鍙戦�佽鏁扮粍鐨勭殑鍏冪礌
	String[] books = new String[] { "杞婚噺绾2EE浼佷笟搴旂敤瀹炴垬", "鍩轰簬J2EE鐨凙jax瀹濆吀",
			"Struts2鏉冨▉鎸囧崡", "ROR鏁忔嵎寮�鍙戞渶浣冲疄璺�" };
	String msg = "<181>ITE-View[1826]: ITE-View[14077231] add DEV00098 DS0026-2-1 [杩愬煄S6506-鐗╄祫灞�]::[219.149.136.99]::[Vlan-interface110] 2011-10-26 23:59:05 2011-10-26 23:59:05 NA NA YC-YHQ-WZJ-DSW-1.MAN.S6506 IFNET/5/UPDOWN:Line protocol on the interface Vlan-interface110 is UP";
	private Logger sendLog = MyLog.getInstance().getSendLog();
	
	public void init() throws IOException {
		try {
			inPacket = new DatagramPacket(inBuff, inBuff.length,
					InetAddress.getByName(IP), PORT);
			// 鍒涘缓DatagramSocket瀵硅薄
			socket = new DatagramSocket();
			// 閲囩敤寰幆鎺ュ彈鏁版嵁
			int i = 0;
			while (true) {
				i++;
				// 浠庡瓧绗︿覆鏁扮粍涓彇鍑轰竴涓厓绱犱綔涓哄彂閫佺殑鏁版嵁
				//byte[] sendData = (i + "---------------" + books[i % 4]).getBytes();
				byte[] sendData = (i + "---------------" + msg).getBytes();
				// 浠ユ寚瀹氬瓧鑺傛暟缁勪綔涓哄彂閫佹暟鎹�佷互鍒氭帴鍙楀埌鐨凞atagramPacket鐨�
				// 婧怱ocketAddress浣滀负鐩爣SocketAddress鍒涘缓DatagramPacket銆�
				outPacket = new DatagramPacket(sendData, sendData.length,inPacket.getSocketAddress());
				// 鍙戦�佹暟鎹�
				socket.send(outPacket);
				sendLog.info(new String(sendData));
				//Thread.sleep(1);///闄愬埗浼犺緭閫熷害
				if (i % 100 == 0) {
					Thread.sleep(5 * 1000);
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 浣跨敤finally鍧椾繚璇佸叧闂祫婧�
		finally {
			if (socket != null) {
				socket.close();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		new MyUdpServer().init();
	}
}
